/*
 * usb_dev.c
 *
 *  Created on: 9 Mar 2010
 *      Author: bob
 */

#include <stdio.h>
#include "libusb.h"
#include "usb_dev.h"

// The one and only USB device handle
libusb_device_handle *handle = NULL;

// PUBLIC

int open_dev(void) {

    // Init library
    libusb_init(NULL); 	// initialize the library
    int r;
    if((handle = libusb_open_device_with_vid_pid(NULL, MY_VID, MY_PID)) != NULL) {
        if((r=libusb_set_configuration(handle, 1)) == 0) {
            if((r=libusb_claim_interface(handle, 0)) == 0) {
                if((r=libusb_set_interface_alt_setting(handle, 0, 0)) == 0) {
                    if((r=libusb_clear_halt(handle, 0x86)) == 0) {
                        if((r=libusb_clear_halt(handle, 0x2)) == 0) {
                            return true;
                        }
                    }
                }
            }
            else {
                printf("Failed to claim interface for usb device [%d]\n", r);
            }
        }
        else {
            printf("Failed to set configuration for usb device [%d]\n", r);
        }
    }
    else {
        printf("Failed to open usb device\n");
    }
    return false;
}

void close_dev(void) {

    if(handle != NULL) {
        libusb_release_interface(handle, 0);
        libusb_close(handle);
        libusb_exit(NULL);
    }
}

int bulk_read(int endpoint, unsigned char *buf, int size, int *transferred, unsigned int timeout) {
    unsigned char ep = (unsigned char)endpoint;
	return libusb_bulk_transfer(handle, ep, buf, size, transferred, timeout);
}

int bulk_write(int endpoint, unsigned char *buf, int size, int *transferred, unsigned int timeout) {
    unsigned char ep = (unsigned char)endpoint;
	return libusb_bulk_transfer(handle, ep, buf, size, transferred, timeout);
}
